package com.vtb.listener;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.vtb.base.VtbDaoFactory;
import com.vtb.entity.DataCache;
import com.vtb.entity.MessageCount;
import com.vtb.entity.QqOauth;
import com.vtb.entity.RrOauth;
import com.vtb.entity.SsOauth;
import com.vtb.entity.Var;
import com.vtb.servlet.WtbException;
import com.vtb.utils.DateUtils;
import com.vtb.utils.JdbcUtils;

public class DateInitAndSaveListener implements ServletContextListener {
	private static final Log log = LogFactory.getLog(DateInitAndSaveListener.class);
	public void contextDestroyed(ServletContextEvent sce) {}
	@SuppressWarnings("unchecked")
    public void contextInitialized(ServletContextEvent sce) {
		VtbDaoFactory daoFactory = VtbDaoFactory.getInstance();
		int value = 0;
		//初始化数据库内数据
		List<QqOauth> qqList = null;
		List<RrOauth> rrList = null;
		List<SsOauth> ssList = null;
		MessageCount messageCount = new MessageCount();
		messageCount.setUni("count");
		try {
			qqList = daoFactory.getDao(Var.QQDAO).getAll();
			rrList = daoFactory.getDao(Var.RRDAO).getAll();
			ssList = daoFactory.getDao(Var.SSDAO).getAll();
			messageCount = (MessageCount) daoFactory.getDao(Var.OTDAO).get(messageCount);
		} catch (Exception e) {
			log.error("数据初始化异常：", e);
			throw new WtbException("数据初始化异常",e);
		}finally{
			JdbcUtils.close();
		}
	
		int i = qqList.size() >= rrList.size() ? qqList.size() : rrList.size();
		value = i >= ssList.size() ? i : ssList.size();
		for(QqOauth qqOauth : qqList){
			DataCache.qqmap.put(qqOauth.getUni(), qqOauth);
			DataCache.qqlastTime.put(qqOauth.getUni(), DateUtils.systemTime());
			log.info("QQ数据初始化成功！！");
		}
		for (RrOauth rrOauth : rrList) {
			DataCache.rrmap.put(rrOauth.getUni(), rrOauth);
			DataCache.rrlastTime.put(rrOauth.getUni(), DateUtils.createTime());
			log.info("人人数据初始化成功！！");
		}
		for(SsOauth ssOauth : ssList){
            DataCache.ssmap.put(ssOauth.getUni(), ssOauth);
            DataCache.qqlastTime.put(ssOauth.getUni(), DateUtils.createTime());
            log.info("SS数据初始化成功！！");
        }
		
		//初始化用户数量
		DataCache.increment(value);
		DataCache.mcountIncrement(Integer.valueOf(messageCount.getPara()));
	}

}
